// import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getRoleList, getRoleUpdate, getRoleDelete,} from "@/api/user";
import { ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import { delay, useWatermark } from "@pureadmin/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { sessionKey } from "@/utils/auth";
import type { PaginationProps, LoadingConfig } from "@pureadmin/table";
import { storageSession } from "@pureadmin/utils";
import { initRouter } from "@/router/utils";
import * as CryptoJS from "crypto-js";
import { getSessionKey } from "@/utils/auth";
import { reactive, ref, computed, onMounted, inject } from "vue";
import {roleList,delAsyncRole} from '@/api/routes'
// import { number } from "echarts/core";

export function useRole(waterRef: Ref) {
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const router = useRouter();
  const refresh: any = inject("reload");
  interface StorageConfigs {
    role_id: number;
  }
  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 20, 30],
    total: 0,
    align: "right",
    background: true,
    small: false
  });

  /** 加载动画配置 */
  const loadingConfig = reactive<LoadingConfig>({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
    // svg: "",
    // background: rgba()
  });
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "角色ID",
      prop: "role_id",
      minWidth: 50
    },
    {
      label: "角色名称",
      prop: "role_name",
      minWidth: 150
    },
    {
      label: "角色描述",
      prop: "role_desc",
      minWidth: 150
    },
    // {
    //   label: "创建时间",
    //   minWidth: 180,
    //   prop: "createTime",
    //   formatter: ({ createTime }) =>
    //     dayjs(createTime).format("YYYY-MM-DD HH:mm:ss")
    // },
    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  /**修改角色状态 */
  async function handleUpdate(row) {
    const res = getRoleUpdate(row);
    console.log(row, res);
  }
  /**删除角色 */
  async function handleDelete(row) {
    const idname = { role_id: row.role_id };
    // const idnameJson = JSON.stringify(idname);
    // const idnameBase64 = CryptoJS.enc.Base64.stringify(
    //   CryptoJS.enc.Utf8.parse(idnameJson)
    // );
    // const idnameValue = {
    //   value: idnameBase64
    // };
    const res = await delAsyncRole(idname);
    if (res.code == 200) {
      message("删除成功", { type: "success" });
      refresh();
    } else {
      message(res.msg, { type: "error" });
    }
  }
  function handleaddUser() {
    console.log("dshfjskdhf");
  }
  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function onCurrentChange(val) {
    loadingConfig.text = `正在加载第${val}页...`;
    loading.value = true;
    delay(600).then(() => {
      loading.value = false;
    });
  }
  //获取角色列表
  async function onSearch(roleid) {
    loading.value = true;
    const roleId =
      storageSession().getItem<StorageConfigs>(sessionKey)?.role_id;
    const roleIdString = {
      role_name: roleid,
      role: roleId
    };
    // const roleIdJson = JSON.stringify(roleIdString);
    // const roleIdBase64 = CryptoJS.enc.Base64.stringify(
    //   CryptoJS.enc.Utf8.parse(roleIdJson)
    // );
    // const roleIdValue = {
    //   value: roleIdBase64
    // };
    const roleIdValue = {
      ...roleIdString,
      page:1,
      pagesize:10
    };
    const { data } = await roleList(roleIdValue);
    dataList.value = data.data
    pagination.total = data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  //获取角色dataList
  async function handleList() {
    let params={
      role_name:''
    }
    const res = await roleList(params);
    if (res.code === 200) {
      dataList.value = res.data.data
      pagination.total = res.data.total;
      setTimeout(() => {
        loading.value = false;
      }, 500);
    } else {
      message(res.msg, { type: "error" });
    }
  }
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    location.reload();
  };

  onMounted(() => {
    delay().then(() => {
      // https://pure-admin-utils.netlify.app/hooks/useWatermark/useWatermark.html
      const { setWatermark } = useWatermark(
        waterRef.value.getTableDoms().tableWrapper
      );
      //水印
      setWatermark("后台项目", {
        font: "16px Microsoft YaHei",
        globalAlpha: 0.8,
        forever: true,
        width: 252,
        height: 80
      });
    });
    handleList();
  });

  return {
    loading,
    columns,
    dataList,
    pagination,
    buttonClass,
    onSearch,
    resetForm,
    handleaddUser,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onCurrentChange
  };
}
